﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RemoterCheckService
{
    public class HttpServer
    {
        HttpListener httpListener = new HttpListener();

        public HttpServer(){
            
        }

        public void Setup(int port=8080)
        {
            if (httpListener == null)
                httpListener = new HttpListener();
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add(string.Format("http://*:{0}/",port));//如果发送到8080 端口没有被处理，则这里全部受理，+是全部接收
            httpListener.Start();//开启服务

            Receive();//异步接收请求
        }

        public void Dispose()
        {
            httpListener.Stop();
            httpListener = null;
        }




        private void Receive()
        {
            httpListener.BeginGetContext(new AsyncCallback(EndReceive), null);
        }

        void EndReceive(IAsyncResult ar)
        {
            var context = httpListener.EndGetContext(ar);
            DealRequest(context);//解析请求
            Receive();
        }

        void DealRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;

            string responseBody = GetResponseBody();

            HttpListenerResponse response = context.Response;
            response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody);
            response.ContentType = "text/html; Charset=UTF-8";
            //输出响应内容
            Stream output = response.OutputStream;
            using (StreamWriter sw = new StreamWriter(output))
            {
                sw.Write(responseBody);
            }
        }

        string GetResponseBody()
        {
            RemoteState remoteState = RemoteCheck.GetRemoteState();
            if (remoteState.IsRemoted)
            {
                string result = "Be Remoted：" + remoteState.RemoterIp;
                return result;
            }
            else
            {
                string result = "Not Remoted.";
                return result;
            }
        }

    }

}
